package com.spring.boot.center.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@MapperScan(basePackages = SqlServerDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "springSqlSessionFactory")
public class SqlServerDataSourceConfig {
	static final String PACKAGE = "com.spring.boot.center.mapper";
//	static final String MAPPER_LOCATION = "classpath*:mapper/*.xml";

	@Value("${spring.datasource.url}")
	private String url;

	@Value("${spring.datasource.username}")
	private String user;

	@Value("${spring.datasource.password}")
	private String password;

	@Value("${spring.datasource.driverClassName}")
	private String driverClass;

	@Bean(name = "springDataSource")
	@Primary
	public DataSource springDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driverClass);
		dataSource.setUrl(url);
		dataSource.setUsername(user);
		dataSource.setPassword(password);
		return dataSource;
	}

	@Bean(name = "springTransactionManager")
	@Primary
	public DataSourceTransactionManager springTransactionManager() {
		return new DataSourceTransactionManager(springDataSource());
	}

	@Bean(name = "springSqlSessionFactory")
	@Primary
	public SqlSessionFactory springSqlSessionFactory(@Qualifier("springDataSource") DataSource masterDataSource) throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(masterDataSource);
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
		sessionFactory.setConfiguration(configuration);
//		sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(SqlServerDataSourceConfig.MAPPER_LOCATION));
		return sessionFactory.getObject();
	}
}
